package com.zadtek.shopmall.activities;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.zack.paymoudle.PayFade;
import com.zack.paymoudle.PayResultListener;
import com.zack.paymoudle.alipay.AlipayConfig;
import com.zack.paymoudle.alipay.OrderInfoTool;
import com.zadtek.shopmall.R;
import com.zadtek.shopmall.base.AbsActivity;
import com.zadtek.shopmall.bean.OrderDetailBean;
import com.zadtek.shopmall.bean.OrderShopItem;
import com.zadtek.shopmall.net.BaseObserver;
import com.zadtek.shopmall.net.BaseResponse;
import com.zadtek.shopmall.net.NetTool;
import com.zadtek.shopmall.utils.ToastUtil;

import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class OrderActivity extends AbsActivity implements View.OnClickListener {
    private TextView tvNamePhone;
    private TextView tvAddress;
    private LinearLayout llShopContainer;
    private TextView tvPayMode;
    private LinearLayout llContainer1;
    private TextView tvRedEnvelopNum;
    private TextView tvRedEnvelop;
    private LinearLayout llContainer2;
    private TextView tvCouponNum;
    private TextView tvCoupon;
    private LinearLayout llContainer3;
    private LinearLayout llContainer4;
    private TextView tvIntergralNum;
    private TextView tvIntergral;
    private TextView tvBuyPrice;
    private LinearLayout llRedContainer;
    private TextView tvUseRedEnvelop;
    private LinearLayout llCouponContainer;
    private TextView tvUserCoupon;
    private LinearLayout llIntergralContainer;
    private TextView tvUseIntergral;
    private TextView tvRealPay;
    private TextView tvBtnPay;
    private TextView tvBtnCancel;
    private ImageView ivBack;
    private TextView title;
    private OrderDetailBean orderBean;

    private String order_sn;

    private void initView() {
        tvNamePhone = (TextView)findViewById( R.id.tv_name_phone );
        tvAddress = (TextView)findViewById( R.id.tv_address );
        llShopContainer = (LinearLayout)findViewById( R.id.ll_shop_container );
        tvPayMode = (TextView)findViewById( R.id.tv_pay_mode );
        llContainer1 = (LinearLayout)findViewById( R.id.ll_container1 );
        tvRedEnvelopNum = (TextView)findViewById( R.id.tv_red_envelop_num );
        tvRedEnvelop = (TextView)findViewById( R.id.tv_red_envelop );
        llContainer2 = (LinearLayout)findViewById( R.id.ll_container2 );
        tvCouponNum = (TextView)findViewById( R.id.tv_coupon_num );
        tvCoupon = (TextView)findViewById( R.id.tv_coupon );
        llContainer3 = (LinearLayout)findViewById( R.id.ll_container3 );
        llContainer4 = (LinearLayout)findViewById( R.id.ll_container4 );
        tvIntergralNum = (TextView)findViewById( R.id.tv_intergral_num );
        tvIntergral = (TextView)findViewById( R.id.tv_intergral );
        tvBuyPrice = (TextView)findViewById( R.id.tv_buy_price );
        llRedContainer = (LinearLayout)findViewById( R.id.ll_red_container );
        tvUseRedEnvelop = (TextView)findViewById( R.id.tv_use_red_envelop );
        llCouponContainer = (LinearLayout)findViewById( R.id.ll_coupon_container );
        tvUserCoupon = (TextView)findViewById( R.id.tv_user_coupon );
        llIntergralContainer = (LinearLayout)findViewById( R.id.ll_intergral_container );
        tvUseIntergral = (TextView)findViewById( R.id.tv_use_intergral );
        tvRealPay = (TextView)findViewById( R.id.tv_real_pay );
        tvBtnPay = (TextView)findViewById( R.id.tv_btn_pay );
        tvBtnCancel = (TextView)findViewById( R.id.tv_btn_cancel );
        ivBack = (ImageView) findViewById(R.id.ic_back);
        ivBack.setVisibility(View.VISIBLE);
        title = (TextView) findViewById(R.id.title);
        title.setText("订单详情");
    }

    @Override
    public int setView() {
        return R.layout.activity_order;
    }

    @Override
    public void initBasic(Bundle savedInstanceState) {
        order_sn = getIntent().getStringExtra("order_sn");
        if(TextUtils.isEmpty(order_sn)){
            ToastUtil.showToast("订单号为空！");
        }
        initView();
        initLogic();
        requestData();
    }

    private void requestData() {
        Map<String, Object> param = NetTool.newParams();
        param.put("uid", 44);
        param.put("order_sn","2017041610583559074");
        NetTool.getApi().getOrder(param)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse<OrderDetailBean>>(this) {
                    @Override
                    public void onData(BaseResponse<OrderDetailBean> value) {
                        if(value.getCode() == 0 && value.getData()!=null){
                            orderBean = value.getData();
                            updateView();
                        }
                    }
                });
//        orderBean = new OrderDetailBean();
//        orderBean.setReductionCoupon(45.00f);
//        orderBean.setReductionRedEnvelop(45.00f);
//        orderBean.setReductionIntergral(48);
//        orderBean.setOrdertotalprice(666.00f);
//        orderBean.setRealPayPrice(555.00f);
//        orderBean.setPayMode(1);
//        orderBean.setOrderstatus(1);
//        AddressItem addressItem = new AddressItem();
//        addressItem.setPhone("15680487267");
//        addressItem.setName("zackdk");
//        addressItem.setAddressDetail("四川省龙泉驿区十陵成都大学");
//        orderBean.setAddressinfo(addressItem);
//
//        SubmitOrderShopItem shopItem = new SubmitOrderShopItem();
//        shopItem.setShopname("旗舰店");
//        shopItem.setDeliverMode("卖家配送");
//        shopItem.setTotalNum(1);
//        shopItem.setTotalPrice(66.00f);
//        List<SubmitOrderProductItem> productList = new LinkedList<>();
//        SubmitOrderProductItem item = new SubmitOrderProductItem();
//        item.setBuyNum(1);
//        item.setProductPrice(45.00f);
//        item.setProductTitle("曼秀雷敦（Mentholatum）控油抗痘洁面乳150ml（男士洗面奶 洁面 控油）");
//        item.setProductImgUrl("http://tc.zadtek.com/aaa/images/201512/thumb_img/336_thumb_G_1449795461300.jpg");
//        productList.add(item);
//        shopItem.setProductItems(productList);
//
//        List<SubmitOrderShopItem> shopItemList = new LinkedList<>();
//
//        shopItemList.add(shopItem);
//        shopItemList.add(shopItem);
//        orderBean.setShops(shopItemList);
//        Gson gson = new Gson();
//        String json = gson.toJson(orderBean);
//        updateView();
    }

    private void updateView() {
        tvNamePhone.setText(orderBean.getAddress().getConsignee()+"        "+orderBean.getAddress().getMobile());
        tvAddress.setText(orderBean.getAddress().getArea());
        tvRedEnvelop.setText(String.valueOf(orderBean.getBonus()));
        //更新发票信息
        llContainer4.setVisibility(View.GONE);
        //

        llContainer2.setVisibility(View.GONE);
        llCouponContainer.setVisibility(View.GONE);
//        if(orderBean.getBonus() == 0){
//        }else{
//            llContainer2.setVisibility(View.VISIBLE);
//            llCouponContainer.setVisibility(View.VISIBLE);
//            tvCoupon.setText("减免￥"+String.valueOf(orderBean.getBonus()));
//            tvUserCoupon.setText("-￥"+String.valueOf(orderBean.getBonus()));
//        }
        if(orderBean.getBonus() == 0){
            llContainer1.setVisibility(View.GONE);
            llRedContainer.setVisibility(View.GONE);
        }else{
            llContainer1.setVisibility(View.VISIBLE);
            llRedContainer.setVisibility(View.VISIBLE);
            tvRedEnvelop.setText("优惠￥"+String.valueOf(orderBean.getBonus()));
            tvUseRedEnvelop.setText("-￥"+String.valueOf(orderBean.getBonus()));
        }
        if(orderBean.getIntegral_money() == 0){
            llContainer3.setVisibility(View.GONE);
            llIntergralContainer.setVisibility(View.GONE);
        }else{
            llContainer3.setVisibility(View.VISIBLE);
            llIntergralContainer.setVisibility(View.VISIBLE);
            tvIntergral.setText("积分抵扣￥"+String.valueOf(orderBean.getIntegral_money()));
            tvUseIntergral.setText("-￥"+String.valueOf(orderBean.getIntegral_money()));
        }

//        int payMode = orderBean.getPayMode();
//        if(payMode == 1){
//            tvPayMode.setText("货到付款");
//        }else if(payMode == 2){
//            tvPayMode.setText("支付宝支付");
//        }else if(payMode == 3){
//            tvPayMode.setText("微信支付");
//        }else if(payMode == 4){
//            tvPayMode.setText("余额支付");
//        }
        tvPayMode.setText(orderBean.getPay_name());
        if(orderBean.getOrder_status() == 1){
        }else if(orderBean.getOrder_status() == 2){
            tvBtnPay.setText("未发货");
            tvBtnCancel.setText("取消订单");
            tvBtnPay.setClickable(false);
        }else if(orderBean.getOrder_status() == 3){
            tvBtnPay.setText("未验收");
            tvBtnCancel.setText("取消订单");
            tvBtnPay.setClickable(false);
        }else if(orderBean.getOrder_status() == 4){
            tvBtnPay.setText("已完成");
            tvBtnCancel.setText("删除订单");
            tvBtnPay.setClickable(false);
        }

        tvBuyPrice.setText("￥"+orderBean.getOrder_amount());
        tvRealPay.setText("￥"+orderBean.getOrder_amount());

        updateShopView(orderBean.getOrder());

    }


    private void updateShopView(List<OrderShopItem> shopItemList) {
        for(int i = 0;i<shopItemList.size();i++){
            final OrderShopItem shopItem = shopItemList.get(i);
            View v = getLayoutInflater().inflate(R.layout.submitorder_item,null);
            TextView shopName = (TextView) v.findViewById(R.id.tv_shop_name);
            TextView totalProductNum = (TextView) v.findViewById(R.id.tv_total_product);
            TextView deliverMode = (TextView) v.findViewById(R.id.tv_deliver_mode);
            LinearLayout container = (LinearLayout) v.findViewById(R.id.ll_product_container);
            v.findViewById(R.id.ll_message_container).setVisibility(View.GONE);
            shopName.setText(shopItem.getShop_name());
            deliverMode.setText(shopItem.getPay_type());
            totalProductNum.setText("共"+shopItem.getGoods_number()+"件商品    合计：￥"+shopItem.getTotal());
            updateProductList(shopItem.getProduct(),container,i);
            llShopContainer.addView(v);
        }
    }

    private void updateProductList(List<OrderShopItem.OrderProudctItem> productItems, LinearLayout container, final int shopPosition) {
        for(int i =0;i<productItems.size();i++){
            OrderShopItem.OrderProudctItem item = productItems.get(i);
            View v = getLayoutInflater().inflate(R.layout.submit_product_item,null);
            ImageView img = (ImageView) v.findViewById(R.id.iv_product_img);
            TextView price = (TextView) v.findViewById(R.id.tv_product_price);
            TextView title = (TextView) v.findViewById(R.id.tv_product_title);
            TextView num = (TextView) v.findViewById(R.id.tv_product_num);
            price.setText("￥"+String.valueOf(item.getGoods_price()));
            Glide.with(mActivity).load(item.getGoods_img()).placeholder(R.drawable.placeholder).into(img);
            title.setText(item.getGoods_name());
            num.setText("x "+item.getGoods_number());
            final int finalI = i;
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ToastUtil.showToast("shopPosition:"+shopPosition+" productPosition:"+ finalI);
                }
            });
            container.addView(v);
        }
    }
    private void initLogic() {
        tvRedEnvelop.setOnClickListener(this);
        tvBtnCancel.setOnClickListener(this);
        tvBtnPay.setOnClickListener(this);
        ivBack.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.ic_back:
                finish();
                break;
            case R.id.tv_btn_cancel:
                ToastUtil.showToast("取消订单请求！");
                break;
            case R.id.tv_btn_pay:
                //payRequest();
                startActivity(new Intent(this,PayOrderActivity.class));
                break;
        }
    }

    private void payRequest() {
        ToastUtil.showToast("支付！");
        PayFade payFade = new PayFade(new PayResultListener() {
            @Override
            public void onPaySuccess() {

            }

            @Override
            public void onPayConfirming() {

            }

            @Override
            public void onPayFailure() {

            }
        });
        AlipayConfig.Builder builder = new AlipayConfig.Builder();
        AlipayConfig config = builder.with(this)
                .setOrderInfo(OrderInfoTool.getOrderInfo("1.00","title","nothing"))
                .useSandBox(true)
                .build();
        payFade.pay(config);
    }
}
